package com.ycsj.goldmedalnewconcept.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.CodeResponse;
import com.ycsj.goldmedalnewconcept.bean.RegisterResponse;
import com.ycsj.goldmedalnewconcept.constant.Constant;

import org.json.JSONObject;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

//注册
public class RegisterActivity extends Activity implements OnClickListener {

	private String account = "";
	
	private String password;
	
	private String code;
	
	private String role;
	
	private ImageView img_back;
	
	private TextView txt_title;
	
	private TextView tv_reg;
	
	private EditText et_user;
	
	private EditText et_password;
	
	private EditText et_code;
	
	private TextView tv_getcode;
	
	private EventHandler eventHandler;
	
	private static final int CODE_ING = 1; // 已发送，倒计时
	
	private static final int CODE_REPEAT = 2; // 重新发送
	
	private static final int SMSDDK_HANDLER = 3; // 短信回调
	
	private int TIME = 300;// 倒计时60s
	
	private MyHandler mhandler;
	
	private Intent intent;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_register);
		
		mhandler = new MyHandler();
		
		intent = getIntent();
		
		role = intent.getStringExtra("role");
		
		initView();
		
		setListener();
		
		initData();
		
		initSDK();
		
	}

	// 初始化SMSSDK
	private void initSDK() {
		
//		SMSSDK.initSDK(this, "1c0fb7d169430",
//				"e0959918dc71b61b493927d6e8f67ab4");
//		MobSDK.init(this, "1c0fb7d169430", "e0959918dc71b61b493927d6e8f67ab4");
		eventHandler = new EventHandler() {
			@Override
			public void afterEvent(int event, int result, Object data) {
				Message msg = new Message();
				msg.arg1 = event;
				msg.arg2 = result;
				msg.obj = data;
				msg.what = SMSDDK_HANDLER;
				handler.sendMessage(msg);
			}
		};
		// 注册回调监听接口
//		SMSSDK.registerEventHandler(eventHandler);
	}

	Handler handler = new Handler() {
		
		public void handleMessage(Message msg) {
			
			switch (msg.what) {
			case CODE_ING:// 已发送,倒计时
				tv_getcode.setText("重新发送(" + --TIME + "s)");
				break;
			case CODE_REPEAT:// 重新发送
				tv_getcode.setText("获取验证码");
				tv_getcode.setClickable(true);
				TIME = 300;
				break;
			case SMSDDK_HANDLER:
				int event = msg.arg1;
				int result = msg.arg2;
				Object data = msg.obj;
				// 回调完成
				if (result == SMSSDK.RESULT_COMPLETE) {
					// 验证码验证成功
					if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
//						Toast.makeText(RegisterActivity.this, "验证成功!正在为您注册",
//								0).show();

//						register(); // 注册
					}
					// 已发送验证码
					else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
//						Toast.makeText(getApplicationContext(), "验证码已经发送至您的手机",
//								Toast.LENGTH_SHORT).show();
					} else {
						((Throwable) data).printStackTrace();
					}
				}
				
				if (result == SMSSDK.RESULT_ERROR) {
					try {
						Throwable throwable = (Throwable) data;
						throwable.printStackTrace();
						JSONObject object = new JSONObject(
								throwable.getMessage());
						String des = object.optString("detail");// 错误描述
						int status = object.optInt("status");	// 错误代码
						if (status > 0 && !TextUtils.isEmpty(des)) {
							Toast.makeText(getApplicationContext(), des,
									Toast.LENGTH_SHORT).show();
							return;
						}
					} catch (Exception e) {
						// do something
					}
				}
				break;
			}
		}
	};

	public void onResume() {
		super.onResume();
	}

	public void onPause() {
		super.onPause();
	}

	private void initView() {
		
		img_back = (ImageView) findViewById(R.id.img_back);
		
		txt_title = (TextView) findViewById(R.id.txt_title);
		
		tv_reg = (TextView) findViewById(R.id.tv_reg);
		
		et_user = (EditText) findViewById(R.id.et_user);
		
		et_password = (EditText) findViewById(R.id.et_password);
		
		tv_getcode = (TextView) findViewById(R.id.tv_getcode);
		
		et_code = (EditText) findViewById(R.id.et_code);
		
	}

	private void setListener() {
		
		img_back.setOnClickListener(this);
		
		tv_reg.setOnClickListener(this);
		
		tv_getcode.setOnClickListener(this);
		
	}

	private void initData() {
		
		img_back.setVisibility(img_back.VISIBLE);
		
		txt_title.setText("注册");
		
	}

	@Override
	public void onClick(View v) {
		
		switch (v.getId()) {
		
		case R.id.img_back: // 返回
			
			finish();
			
			break;
			
		case R.id.tv_getcode: // 获取验证码
			
			account = et_user.getText().toString().trim();
			boolean isphone = isChinaPhoneLegal(account); // 正则表达式判断号码
			if ("".equals(account)) {
				Toast.makeText(getBaseContext(), "请先填写手机号码", Toast.LENGTH_SHORT).show();
				return;
			} else if (!isphone) {
				Toast.makeText(getBaseContext(), "手机号码格式不正确", Toast.LENGTH_SHORT).show();
				return;
			}
			   
//			SMSSDK.getVerificationCode("86", account);
			
			//获取验证码
			getCode();
			
			tv_getcode.setClickable(false);
		

			break;
		case R.id.tv_reg: // 注册
			password = et_password.getText().toString().trim();
			code = et_code.getText().toString().trim();
			
			if (password==null||"".equals(password)) {
				Toast.makeText(getBaseContext(), "请输入6-20位数字或者字母", Toast.LENGTH_SHORT).show();
				return;
			}
			
			// 正则表达式判断密码
			if(!isPassword(password)){
				Toast.makeText(getBaseContext(), "请输入6-20位数字或者字母", Toast.LENGTH_SHORT).show();
				return;
			}
			
//			boolean s = isChinaPhoneLegal(account); // 正则表达式判断号码
			int passwordlenth = password.length(); 
			if (passwordlenth < 6) {
				Toast.makeText(getBaseContext(), "请输入6-20位数字或者字母", Toast.LENGTH_SHORT).show();
				et_password.setText("");
				et_password.requestFocus();
				return;
			} else if ("".equals(code)) {
				Toast.makeText(getBaseContext(), "请输入短信验证码", Toast.LENGTH_SHORT).show();
				et_code.requestFocus();
				return;
			}else if("".equals(account)){
				Toast.makeText(getBaseContext(), "请获取验证码", Toast.LENGTH_SHORT).show();
				return;
			}
			tv_reg.setClickable(false);
//			SMSSDK.submitVerificationCode("86", account, et_code.getText()
//					.toString());// 对验证码进行验证
			//对验证码进行验证
			submitCode(code);

			break;
		}
	}
	
	//对验证码进行验证
	private void submitCode(String code) {
		
		OkHttpClient mOkHttpClient = new OkHttpClient();
//		 mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "7");		
		builder.add("c", account);		//账号
		builder.add("role", role);		
		builder.add("sms_id", "0");		
		builder.add("code", code);		
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "AccountMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "验证码获取失败，请检查网络连接", Toast.LENGTH_SHORT)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				
				// 解析Json数据，保存登录状态及身份信息 
				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", "json"+json);
				final AttResponse fromJson = gson.fromJson(json,
						AttResponse.class);
				
				if(fromJson!=null){
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							if("-1".equals(fromJson.state)){
								//没有待验证的验证码数据，需要重新发送新的验证码
								Toast.makeText(getBaseContext(), "验证码失效，请重新发送", Toast.LENGTH_SHORT)
								.show();
								tv_reg.setClickable(true);
							}else if("1".equals(fromJson.state)){
								//通过
								
								register(); // 注册
								
							}else if("2".equals(fromJson.state)){
								//验证码不一致（内容比对不一致）
								tv_reg.setClickable(true);
								Toast.makeText(getBaseContext(), "验证码不一致", Toast.LENGTH_SHORT)
								.show();
							}else if("3".equals(fromJson.state)){
								// 验证码失效（未在发送验证码后5分钟内验证）
								tv_reg.setClickable(true);
								Toast.makeText(getBaseContext(), "验证码失效，请重新发送", Toast.LENGTH_SHORT)
								.show();
							}
						}
					});
				}
			}
		});
	}
	
	
	//获取验证码
	private void getCode() {
		
				OkHttpClient mOkHttpClient = new OkHttpClient();
//				 mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				FormEncodingBuilder builder = new FormEncodingBuilder();
				builder.add("type", "1");		
				builder.add("c", account);		//账号
				builder.add("role", role);		
				Request request = new Request.Builder()
//						.url("http://192.168.0.198:8888/ycsj_platform/" + "FilterMsg")
						.url(Constant.SERVER_URL + "FilterMsg")
						.post(builder.build()).build();
				mOkHttpClient.newCall(request).enqueue(new Callback() {
					

					@Override
					public void onFailure(Request arg0, IOException arg1) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(getBaseContext(), "网络错误", Toast.LENGTH_SHORT)
										.show();
							}
						});
					}

					@Override
					public void onResponse(Response arg0) throws IOException {
						
						// 解析Json数据，保存登录状态及身份信息
						Gson gson = new Gson();
						String json = arg0.body().string();
						Log.e("test", "json"+json);
						final CodeResponse fromJson = gson.fromJson(json,
								CodeResponse.class);
						
						if(fromJson!=null){
							
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									if("0".equals(fromJson.sms_state)){
										Toast.makeText(getBaseContext(), "验证码已发送至您的手机", Toast.LENGTH_SHORT)
										.show();
										new Thread(new Runnable() {
											@Override
											public void run() {
												for (int i = 300; i > 0; i--) {
													handler.sendEmptyMessage(CODE_ING);
													if (i <= 0) {
														break;
													}
													try {
														Thread.sleep(1000);
													} catch (InterruptedException e) {
														e.printStackTrace();
													}
												}
												handler.sendEmptyMessage(CODE_REPEAT);
											}
										}).start();
									}else if("-1".equals(fromJson.sms_state)){
										Toast.makeText(getBaseContext(), "发送失败，请联系客服", Toast.LENGTH_SHORT)
										.show();
									}else if("-2".equals(fromJson.sms_state)){
										Toast.makeText(getBaseContext(), "验证码五分钟有效,请查阅短信", Toast.LENGTH_SHORT)
										.show();
									}
								}
							});
						}
					}
				});
	}

	// 注册
	private void register() {
		if(role==null||role.equals("")){
			role = "0";
		}
		// TODO Auto-generated method stub
		OkHttpClient mOkHttpClient = new OkHttpClient();
//		 mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "1");		
		builder.add("c", account);		//账号
		builder.add("p", password);		//密码
		builder.add("role", role);		
		builder.add("platform", "2");	
		builder.add("param", "13451193253");
		Request request = new Request.Builder()
				.url(Constant.SERVER_URL + "AccountMsg")
				.post(builder.build()).build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络错误", Toast.LENGTH_SHORT)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				
				// 解析Json数据，保存登录状态及身份信息
				Gson gson = new Gson();
				String json = arg0.body().string();
				Log.e("test", "json"+json);
				RegisterResponse fromJson = gson.fromJson(json,
						RegisterResponse.class);
				
				Message message = Message.obtain();
				message.arg1 = 0;
				message.obj = fromJson;
				mhandler.sendMessage(message);
			}
		});
	}

	public class MyHandler extends Handler {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			RegisterResponse fromJson = (RegisterResponse) msg.obj;

			tv_reg.setClickable(true);

			if ("exist".equals(fromJson.register)) {
				Toast.makeText(getApplicationContext(), "用户账号已存在，请联系老师或者更换账号注册", Toast.LENGTH_SHORT)
				.show();
				et_password.setText("");
				et_code.setText("");
			} else if("successful".equals(fromJson.register)){
				Toast.makeText(getApplicationContext(), "恭喜您，注册成功！", Toast.LENGTH_LONG)
						.show();
				finish();
				overridePendingTransition(R.anim.hold,R.anim.fade_out_reg);
			}else{
				Toast.makeText(getApplicationContext(), "服务器开小差了", Toast.LENGTH_SHORT)
				.show();
			}
		}
	}
	
	
	// 国内运营商手机号码
	public boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
//		String regExp = "^((13[0-9])|(15[^4])|(18[0,1,2,3,4,5-9])|(17[0-8])|(147))\\d{8}$";
		String regExp = ("^((13[0-9])|(14[0-9])|(15[0-9])|(18[0-9])|(19[0-9])|(17[0-9])|(16[0-9]))\\d{8}$");
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}
	
	private boolean isPassword(String password2) {
		// TODO Auto-generated method stub
		String regExp = ("^[a-zA-Z0-9]{6,20}+$");
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(password2);
		return m.matches();
		
	}
}
